package com.focusai.efairy.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.focusai.efairy.R;
import com.focusai.efairy.model.project.ProjectItem;
import com.focusai.efairy.model.request.GetManageProjectListRequest;
import com.focusai.efairy.model.request.GetProjectListRequest;
import com.focusai.efairy.model.response.ProjectListResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.network.request.base.Request;
import com.focusai.efairy.ui.activity.dev.DeviceListActivity;
import com.focusai.efairy.ui.activity.project.ProjectAddorEditActivity;
import com.focusai.efairy.ui.activity.project.ProjectManagerActivity;
import com.focusai.efairy.ui.activity.project.ProjectMapLocationActivity;
import com.focusai.efairy.ui.activity.report.ReportActivity;
import com.focusai.efairy.ui.adapter.ProjectListAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerViewHolder;
import com.focusai.efairy.ui.base.BaseFragment;
import com.focusai.efairy.ui.widget.SearchTittleView;
import com.focusai.efairy.ui.widget.TitleView;

import java.util.ArrayList;

/**
 * Created by luo_guangwen on 2017/8/13.
 */

public class ProjectFragment extends BaseFragment {
    public static final String OPEN_TYPE = "open_type";
    public static final int REQUEST_CODE_ADD = 0x10;
    public static final int REQUEST_CODE_PRO_DETAIL = 0x11;
    public static final int OPEN_TYPE_PROJECT_MANAGE = 2;
    public static final int OPEN_TYPE_REPORT = 1;

    private TitleView mTitleView;
    private SearchTittleView searchTittleView;
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout layoutRefresh;
    private ImageView tipView;

    private ProjectListAdapter mAdapter;
    private ArrayList<ProjectItem> mList;
    private int openInActivity = 0; //0为首页里面打开，1为报表里打开，2，为项目管理打开

    private int isUserCreateProject = -1;// 0为自己创建的项目，1为他人创建

    public ProjectFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_project, container, false);
        initView(view);
        bindEvents();
        setDefaultValues();
        loadData("");
        layoutRefresh.setRefreshing(true);
        return view;
    }

    @Override
    protected void initView(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.rcyc_view);
        mTitleView = findView(view, R.id.title_view);
        layoutRefresh = findView(view, R.id.layout_refresh);
        searchTittleView = findView(view, R.id.view_tittle_search);
        tipView = findView(view,R.id.iv_no_data);
    }

    @Override
    protected void bindEvents() {
        if (getArguments() != null) {
            openInActivity = getArguments().getInt(OPEN_TYPE, 0);
        }
        TextView textRight = mTitleView.getmTextRight();
        if (openInActivity == 0) {
            textRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ProjectMapLocationActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(ProjectMapLocationActivity.KEY_MAP_ITEMS, mList);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
        } else if (openInActivity == OPEN_TYPE_PROJECT_MANAGE) {
            mTitleView.getmTextRight().setBackgroundDrawable(null);
            mTitleView.getmTextRight().setText(R.string.add);
            mTitleView.getmBack().setVisibility(View.VISIBLE);
            mTitleView.getmRadioGroup().setVisibility(View.VISIBLE);
            mTitleView.getmRbnLeft().setChecked(true);
            mTitleView.getmTextCenter().setVisibility(View.GONE);
            isUserCreateProject = 0;
            mTitleView.getmRadioGroup().setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                    if (checkedId == R.id.title_radio_btn_left) {
                        isUserCreateProject = 0;
                        mTitleView.getmRbnLeft().setTextColor(getResources().getColor(R.color.white));
                        mTitleView.getmRbnRight().setTextColor(getResources().getColor(R.color.main_color));
                        layoutRefresh.setRefreshing(true);
                        loadData("");
                    } else if (checkedId == R.id.title_radio_btn_right) {
                        isUserCreateProject = 1;
                        mTitleView.getmRbnLeft().setTextColor(getResources().getColor(R.color.main_color));
                        mTitleView.getmRbnRight().setTextColor(getResources().getColor(R.color.white));
                        layoutRefresh.setRefreshing(true);
                        loadData("");
                    }
                }
            });
            mTitleView.getmBack().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().finish();
                }
            });
            mTitleView.getmTextRight().setTextColor(getContext().getResources().getColor(R.color.main_color));
            mTitleView.getmTextRight().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent1 = new Intent(getContext(), ProjectAddorEditActivity.class);
                    startActivityForResult(intent1, REQUEST_CODE_ADD);
                }
            });
        } else if (openInActivity == OPEN_TYPE_REPORT) {
            mTitleView.getmTextRight().setVisibility(View.GONE);
            mTitleView.getmBack().setVisibility(View.VISIBLE);
            mTitleView.getmBack().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().finish();
                }
            });
        }
        layoutRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData("");
            }
        });
        searchTittleView.setSearchListener(new SearchTittleView.OnSearchListener() {
            @Override
            public void onStartQuery(String keywork, boolean hideInput) {
                if (hideInput) {
                    hideSoftInput();
                }
                loadData(keywork);
            }

            @Override
            public void onCancalBackClick() {
                mTitleView.setVisibility(View.VISIBLE);
                hideSoftInput();
                loadData("");
            }

            @Override
            public void onEnterInputKeyWork() {
                mTitleView.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected void setDefaultValues() {
        mList = new ArrayList<>();
        mAdapter = new ProjectListAdapter(getContext());
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerItemDecoration itemDecoration = new DividerItemDecoration(getContext(), DividerItemDecoration.HORIZONTAL);
        itemDecoration.setDrawable(new ColorDrawable(getContext().getResources().getColor(R.color.general_grey_line)));
        mRecyclerView.addItemDecoration(itemDecoration);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseRecyclerViewHolder holder) {
                if (holder == null) return;
                int position = mRecyclerView.getChildLayoutPosition(holder.itemView);
                mAdapter.setSelectPosition(position);
                mAdapter.notifyDataSetChanged();
                ProjectItem projectItem = mList.get(position);
                Intent intent;
                if (openInActivity == OPEN_TYPE_PROJECT_MANAGE) {
                    intent = new Intent(getActivity(), ProjectManagerActivity.class);
                    intent.putExtra(ProjectManagerActivity.KEY_PROJECT_ITEM_ID, projectItem.efairyproject_id + "");
                    startActivityForResult(intent, REQUEST_CODE_PRO_DETAIL);
                } else if (openInActivity == OPEN_TYPE_REPORT) {
                    intent = new Intent(getActivity(), ReportActivity.class);
                    intent.putExtra(ReportActivity.KEY_PROJECT_ITEM_ID, projectItem.efairyproject_id + "");
                    intent.putExtra(ReportActivity.KEY_PROJECT_ITEM_NAME, projectItem.efairyproject_name);
                    startActivity(intent);
                } else {
                    intent = new Intent(getActivity(), DeviceListActivity.class);
                    intent.putExtra(DeviceListActivity.PROJECT_ITEM, projectItem);
                    startActivity(intent);
                }

            }
        });
    }

    private void loadData(String keyword) {
        Request request;
        Response.Listener<ProjectListResponse> listener = new Response.Listener<ProjectListResponse>() {
            @Override
            protected void onSuccess(ProjectListResponse response) {
                layoutRefresh.setRefreshing(false);
                if (response != null && response.project_list != null) {
                    mList.clear();
                    mList.addAll(response.project_list);
                    mAdapter.setSelectPosition(-1);
                    mAdapter.refreshData(mList);
                }
                showTip();
            }

            @Override
            protected void onFail(NetworkException exception) {
                layoutRefresh.setRefreshing(false);
                doException(exception);
                showTip();
            }
        };
        if (openInActivity == OPEN_TYPE_PROJECT_MANAGE) {
            request = new GetManageProjectListRequest(keyword,isUserCreateProject,listener);
        } else {
            request = new GetProjectListRequest(keyword, listener);
        }
        HttpManager.getInstance().sendRequest(request);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ADD:
                case REQUEST_CODE_PRO_DETAIL:
                    layoutRefresh.setRefreshing(true);
                    loadData("");
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return searchTittleView.onKeyDown(keyCode, event);
    }

    private void showTip(){
        if (mAdapter.getData() != null && mAdapter.getData().size() > 0){
            tipView.setVisibility(View.GONE);
        }else {
            tipView.setVisibility(View.VISIBLE);
        }
    }
}
